package com.silverhaze.web.job;

import com.silverhaze.web.data.wot.WoTPlayer;
import com.silverhaze.web.data.wot.WoTTank;
import com.silverhaze.web.util.EntityManageUtil;
import com.silverhaze.web.wot.WoTStatisticsParser;
import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.List;

/**
 * User: Babanin
 * Date: 07.01.12
 * Time: 23:45
 */
public class WoTStatisticsJob implements Job {

    private static final Logger LOGGER = Logger.getLogger(WoTStatisticsJob.class);

    public void execute() {
        LOGGER.info("Updating statistics");

        List<WoTTank> woTTanks = EntityManageUtil.load(WoTTank.class);
        List<WoTPlayer> woTPlayers = EntityManageUtil.load(WoTPlayer.class);

        EntityManageUtil.removeDayStatistics(new java.sql.Date(new Date().getTime()));

        for (WoTPlayer player : woTPlayers) {
            LOGGER.info("Checking player: " + player.getUser());
            LOGGER.info("Fetching player statistics");

            StringBuilder builder = new StringBuilder();
            try {
                String line = null;
                BufferedReader dis = new BufferedReader(new InputStreamReader(
                        new URL(player.getWotProfileUrl()).openStream(), "UTF-8"));

                while ((line = dis.readLine()) != null) {
                    builder.append(line);
                }
            } catch (MalformedURLException mue) {
                mue.printStackTrace();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }

            if (builder.length() > 0) {
                WoTStatisticsParser.parse(new WoTStatisticsParser.ParserContext(player, null, woTTanks), builder.toString());
            }
        }
    }
}
